<?php 
	class Tree{
		protected $fid_name;
		protected $id_name;
		protected $arr;
		protected $root_id;
 		protected $icon = array('│','├','└');
 		protected $return_str = "";
		function __construct($arr,$root_id = '0',$fid_name = 'fid',$id_name = '_id'){
			$this->arr = $arr;
			$this->fid_name = $fid_name;
			$this->id_name = $id_name;
			$this->root_id = $root_id;
		}
		function findChild(&$arr,$id){
		    $childs=array();
		     foreach ($arr as $k => $v){
		         if($v[$this->fid_name]== $id){
		              $childs[]=$v;
		         }
		    }
		    return $childs;
		}

		function build_tree_arr(){
		    $childs=$this->findChild($this->arr,$this->root_id);
		    if(empty($childs)){
		        return null;
		    }
		   foreach ($childs as $k => $v){
		       $rescurTree=$this->findChild($v[$this->id_name],$v[$this->fid_name]);
		       if( null !=   $rescurTree){
		       $childs[$k]['childs']=$rescurTree;
		       }
		   }
		    return $childs;
		}
 		
 		function get_tree_str($rid='0',$sid = '0', $adds = ''){
 			$number = 1;
 			$child = $this->findChild($this->arr,$rid);
 			if(is_array($child)){
 				$total = count($child);
 				foreach ($child as $k => $v) {
 					$j=$k='';
 					if($v[$this->fid_name] != "0"){//如果无上级，则不要前面的符号
	 					if($number == $total){
	 						 $j .= $this->icon[2];
	 					}else{
		                    $j .= $this->icon[1];
		                }
		            }
	                $k = $adds ? $adds : '';
	                $this->return_str .= "<option value='".$v['_id']."'>".$k.$j.$v['name']."</option>";
	                $this->get_tree_str($v['_id'], $sid, $adds.$k.'&nbsp;&nbsp;');
 					$number ++;
 				}
 			}
			return $this->return_str;
 		}

		function get_tree_arr($rid='0',$sid = '0', $adds = ''){
 			$number = 1;
 			$child = $this->findChild($this->arr,$rid);
 			if(is_array($child)){
 				$total = count($child);
 				foreach ($child as $k => $v) {
 					$j=$k='';
 					if($v[$this->fid_name] != "0"){//如果无上级，则不要前面的符号
	 					if($number == $total){
	 						 $j .= $this->icon[2];
	 					}else{
		                    $j .= $this->icon[1];
		                }
	            	}
	                $k = $adds ? $adds : '';
	                $this->return_str[] = $k.$j.$v['name'];
	                $this->get_tree_arr($v['_id'], $sid, $adds.$k.'&nbsp;&nbsp;');
 					$number ++;
 				}
 			}
			return $this->return_str;
 		}


	}
?>